import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useSignalRStore } from './signalr'

export const useAuthStore = defineStore('auth', () => {
  const router = useRouter()
  const signalRStore = useSignalRStore()
  
  const token = ref(localStorage.getItem('auth_token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user_info') || 'null'))
  const serverUrl = ref(localStorage.getItem('server_url') || 'https://localhost:7001')
  
  const isAuthenticated = computed(() => !!token.value)
  
  // 登录
  const login = async (credentials) => {
    try {
      // 模拟登录API调用
      const response = await mockLogin(credentials)
      
      if (response.success) {
        token.value = response.token
        user.value = response.user
        
        // 保存到本地存储
        localStorage.setItem('auth_token', response.token)
        localStorage.setItem('user_info', JSON.stringify(response.user))
        
        // 连接SignalR
        await signalRStore.connect(serverUrl.value, token.value)
        
        router.push('/main')
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: '登录失败，请检查网络连接' }
    }
  }
  
  // 退出登录
  const logout = async () => {
    // 断开SignalR连接
    await signalRStore.disconnect()
    
    // 清除本地数据
    token.value = ''
    user.value = null
    localStorage.removeItem('auth_token')
    localStorage.removeItem('user_info')
    
    router.push('/login')
  }
  
  // 检查自动登录
  const checkAutoLogin = async () => {
    if (token.value && user.value) {
      try {
        // 验证token有效性（模拟）
        const isValid = await mockValidateToken(token.value)
        if (isValid) {
          await signalRStore.connect(serverUrl.value, token.value)
          router.push('/main')
        } else {
          await logout()
        }
      } catch (error) {
        console.error('自动登录失败:', error)
        await logout()
      }
    }
  }
  
  // 设置服务器地址
  const setServerUrl = (url) => {
    serverUrl.value = url
    localStorage.setItem('server_url', url)
  }
  
  return {
    token,
    user,
    serverUrl,
    isAuthenticated,
    login,
    logout,
    checkAutoLogin,
    setServerUrl
  }
})

// 模拟登录API
const mockLogin = async (credentials) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      if (credentials.username === 'admin' && credentials.password === '123456') {
        resolve({
          success: true,
          token: 'mock_token_' + Date.now(),
          user: {
            id: 1,
            username: credentials.username,
            name: '管理员'
          }
        })
      } else {
        resolve({
          success: false,
          message: '用户名或密码错误'
        })
      }
    }, 1000)
  })
}

// 模拟token验证
const mockValidateToken = async (token) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(token.startsWith('mock_token_'))
    }, 500)
  })
}